import { BActor } from "../Core/BActor";
import vtkActor from "@kitware/vtk.js/Rendering/Core/Actor";
import vtkMapper from "@kitware/vtk.js/Rendering/Core/Mapper";
import { Vector3 } from "@kitware/vtk.js/types";
import vtkPolyData from "@kitware/vtk.js/Common/DataModel/PolyData";
import vtkPoints from "@kitware/vtk.js/Common/Core/Points";
import vtkCellArray from "@kitware/vtk.js/Common/Core/CellArray";
import { ACTOR_TYPE } from "../";

export interface PointsActorOptions {
  points?: Vector3[];
  pointsCell?: vtkPoints;
  color?: number[];
  size?: number;
}

export class PointsActor extends BActor {
  readonly type = ACTOR_TYPE.GRAPHIC_ACTOR;
  createdBy = "default";
  instance: vtkActor;
  mapper: vtkMapper;
  polyData: vtkPolyData = vtkPolyData.newInstance();
  points: vtkPoints = vtkPoints.newInstance();
  cells = vtkCellArray.newInstance();
  constructor(options: PointsActorOptions) {
    super();
    this.instance = vtkActor.newInstance();
    this.mapper = vtkMapper.newInstance();
    if (options.points) {
      const tmp: number[] = [];
      options.points.forEach((t, index) => {
        tmp.push(...t);
        this.cells.insertNextCell([index]);
      });
      this.points.setData(tmp, 3);
    }

    if (options.pointsCell) {
      this.points = options.pointsCell;
      const num = this.points.getNumberOfPoints();
      for (let i = 0; i < num; i++) {
        this.cells.insertNextCell([i]);
      }
    }
    this.polyData.setPoints(this.points);
    this.polyData.setVerts(this.cells);
    this.mapper.setInputData(this.polyData);
    this.instance.setMapper(this.mapper);
    const [r, g, b] = options.color || [1, 0, 0];
    this.instance.getProperty().setColor(r, g, b);
    this.instance.getProperty().setPointSize(options.size || 10);
  }

  get visible() {
    return this.instance.getVisibility();
  }

  set visible(vis: boolean) {
    this.instance.setVisibility(vis);
  }
}
